<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;

class Accommodation extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("id")) {
            $map['id'] = ["like", "%" . $this->request->param("id") . "%"];
        }
        if ($this->request->param("order_id")) {
            $map['order_id'] = ["like", "%" . $this->request->param("order_id") . "%"];
        }
        if ($this->request->param("create_time")) {
            $map['create_time'] = ["like", "%" . $this->request->param("create_time") . "%"];
        }
        if ($this->request->param("remark")) {
            $map['remark'] = ["like", "%" . $this->request->param("remark") . "%"];
        }
    }

    public function index()
    {
        $data = input();
        // 搜索条件
        if ($data['order_id']){
            $oid = '';
            $orders = Db::name('order')->where('order_id',"like","%{$data['order_id']}%")->select();
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if (!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['remark']){
            $map['accommodation'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['start_time']){
            $start_time = strtotime($data['start_time']);
            $orders = Db::name('order')->where('start_time',$start_time)->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['end_time']){
            $end_time = strtotime($data['end_time']);
            $orders = Db::name('order')->where('end_time',$end_time)->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['platform']){
            $orders = Db::name('order')->where('platform',$data['platform'])->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['phone']){
            $map['phone'] = ['like',"%{$data['phone']}%"];
        }
        if ($data['name']){
            $map['name'] = ['like',"%{$data['name']}%"];
        }
        if ($data['booking_people_name']){
            $orders = Db::name('order')->where('booking_people_name','like',"%{$data['booking_people_name']}%")->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['booking_people_phone']){
            $orders = Db::name('order')->where('booking_people_phone','like',"%{$data['booking_people_phone']}%")->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        // 查询数据
        $listRows = $this->request->param('numPerPage') ?: config("paginate.list_rows");
//        $map['group_id']=0;
        $map['isdelete'] = 0;
        $map['isaccommodation'] = '包含住宿';
        $list = Db::name('order_traveler')
            ->where($map)
            ->order('id','desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];

        foreach ($listData as $index => $listDatum) {
            if ($listDatum['group_id']){// 已经派单
                $travellerInfo = Db::name('order_traveler')->where('group_id',$listDatum['group_id'])
                                                ->where('oid',$listDatum['oid'])->where('isaccommodation','包含住宿')
                                                ->order('id','desc')->select();
                $listData[$index]['num'] = count($travellerInfo);
                if (count($travellerInfo) == 1){
                    $listData[$index]['show_single']=true;
                    $listData[$index]['show_mian']=false;
                    $listData[$index]['show_between']=false;
                    $listData[$index]['show_end']=false;
                }elseif ($travellerInfo){
                    $prev = 0;
                    if (($index-1)>=0 && isset($listData[$index-1])){ // 它的前一组，判断是否是同一个组的
                        foreach ($travellerInfo as $index01 => $item01) {
                            if ($listData[$index-1]['id'] == $item01['id']){
                                $prev = 1;
                            }
                        }
                    }
                    $next = 0; // 下一个
                    if (($index+1) <= 19 && isset($listData[$index+1])){
                        foreach ($travellerInfo as $index02 => $item02) {
                            if ($listData[$index+1]['id'] == $item02['id']){
                                $next = 1;
                            }
                        }
                    }
                    if ($next && $prev){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=true;
                        $listData[$index]['show_end']=false;
                    }elseif ($prev){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=true;
                    }elseif ($next){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=true;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=false;
                    }else{
                        $listData[$index]['show_single']=true;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=false;
                    }
                }
            }else{ // 还没有派单
                $travellerInfo = Db::name('order_traveler')
                                        ->where('oid',$listDatum['oid'])
                                        ->where('isaccommodation','包含住宿')
                                        ->order('id','desc')->select();
                $listData[$index]['num'] = count($travellerInfo);
                if (count($travellerInfo) == 1){
                    $listData[$index]['show_single']=true;
                    $listData[$index]['show_mian']=false;
                    $listData[$index]['show_between']=false;
                    $listData[$index]['show_end']=false;
                }elseif ($travellerInfo){
                    $prev = 0;
                    if (($index-1)>=0 && isset($listData[$index-1])){ // 它的前一组，判断是否是同一个组的
                        foreach ($travellerInfo as $index03 => $item03) {
                            if ($listData[$index-1]['id'] == $item03['id']){
                                $prev = 1;
                            }
                        }
                    }
                    $next = 0; // 下一个
                    if (($index+1) <= 19 && isset($listData[$index+1])){
                        foreach ($travellerInfo as $index04 => $item04) {
                            if ($listData[$index+1]['id'] == $item04['id']){
                                $next = 1;
                            }
                        }
                    }
                    if ($next && $prev){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=true;
                        $listData[$index]['show_end']=false;
                    }elseif ($prev){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=true;
                    }elseif ($next){
                        $listData[$index]['show_single']=false;
                        $listData[$index]['show_mian']=true;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=false;
                    }else{
                        $listData[$index]['show_single']=true;
                        $listData[$index]['show_mian']=false;
                        $listData[$index]['show_between']=false;
                        $listData[$index]['show_end']=false;
                    }
                }
            }
        }
        // 对数据进行处理
        if ($listData){
            foreach ($listData as $index022 => $listDatum022) {
                $order = Db::name('order')->where('id',$listDatum022['oid'])->find();
                if ($order){
                    $listData[$index022]['sales_id'] = $order['sales_id'];
                    if ($order['platform'] == 'mfw'){
                        $listData[$index022]['sku_name'] = Db::name('mfw_sku')->where('sku_id',$order['sku_id'])->value('sku_name');
                    }else{
                        $listData[$index022]['sku_name'] = $order['sku_id'];
                    }
                    // 订单状态
                    if ($order['vehicle_adjustment'] == '' && $order['room_adjustment'] == '') {
                        $listData[$index022]['order_processing_status'] = '正常';
                    }elseif ($order['vehicle_adjustment'] == 'Pending disposal' || $order['room_adjustment'] == 'Pending disposal') {
                        $listData[$index022]['order_processing_status'] = '待确认';
                    }elseif ($order['vehicle_adjustment'] == 'Processed' && $order['room_adjustment'] == 'Processed'){
                        $listData[$index022]['order_processing_status'] = '已修改';
                    }elseif ($order['vehicle_adjustment'] == 'Processed' && $order['room_adjustment'] == ''){
                        $listData[$index022]['order_processing_status']= '已修改';
                    }elseif ($order['vehicle_adjustment'] == '' && $order['room_adjustment'] == 'Processed'){
                        $listData[$index022]['order_processing_status'] = '已修改';
                    }
                    // 旅游路线
                    $route = Db::name('route')->where('id',$order['route_id'])->value('title');
                    $listData[$index022]['route_name'] = empty($route)? '旅游路线不存在':$route;
                    $platform = Db::name('platform')->where('platform_name',$order['platform'])->value('name');
                    $listData[$index022]['platform'] = empty($platform)? '平台不存在':$platform;
                    $listData[$index022]['start_time'] = empty($order['start_time'])? '':date('Y-m-d',$order['start_time']);
                    $listData[$index022]['end_time'] = empty($order['end_time'])? '':date('Y-m-d',$order['end_time']);
                    $listData[$index022]['booking_people_name'] = empty($order['booking_people_name'])? '':$order['booking_people_name'];
                    $listData[$index022]['booking_people_phone'] = empty($order['booking_people_phone'])? '':$order['booking_people_phone'];
                    $listData[$index022]['order_no'] = empty($order['order_id'])? '':$order['order_id'];
                    $listData[$index022]['title'] = empty($order['title'])? '':$order['title'];
                }
            }
        }
        $count = count($listData);
        // 查找所有平台数据
        $platformData = Db::name('platform')->select();
        $this->view->assign('list',$listData);
        $this->view->assign('platform',$platformData);
        $this->view->assign('page',$list->render());
        $this->view->assign('count',$count);
        $this->view->assign('searchCondition',$data);//搜索条件
        return $this->view->fetch();
    }

    public function index01()
    {
        $data = input();
        if ($data['create_time']){
            $map['create_time'] = array("between",[strtotime($data['create_time']." 00:00:00"),strtotime($data['create_time']." 23:59:59")]);
        }
        if ($data['is_accommodation'] == 2){
            $map['is_accommodation'] = 1;
        }elseif ($data['is_accommodation'] == 1){
            $map['is_accommodation'] = 0;
        }
        if ($data['remark']){
            $map['remark'] = ['like',"%{$data['remark']}%"];
        }
        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
        $list = Db::name('accommodation')->where($map)->order('id','desc')->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];
        $idArr = [];
        if ($listData){
            foreach ($listData as $index => $listDatum) {
//                $idArr[]
            }
        }
        $count = $list->total();
        $searchCondition = $data;
        return view('',compact('list','count','searchCondition'));
    }

    public function deleteforever()
    {
        $data = input();
        if (!$data['id']){
            return ajax_return_adv_error('缺少参数');
        }
        $del = Db::name('accommodation')->where('id',$data['id'])->delete();
        if ($del){
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_adv_error('删除失败');
        }
    }

    /**
     * 导出数据
     */
    /**
     * 导出数据到excel
     */
    public function get_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['id','游客姓名','游客电话','身份证号','地址','订单id','分组id','年龄','性别','旅游路线','是否住宿','住宿备注','预订人姓名','预订人电话','开始时间','结束时间','平台','标题','客人数量'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }
        // 搜索条件
        if ($data['order_id']){
            $oid = '';
            $orders = Db::name('order')->where('order_id',"like","%{$data['order_id']}%")->select();
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if (!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['remark']){
            $map['accommodation'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['start_time']){
            $start_time = strtotime($data['start_time']);
            $orders = Db::name('order')->where('start_time',$start_time)->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['end_time']){
            $end_time = strtotime($data['end_time']);
            $orders = Db::name('order')->where('end_time',$end_time)->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['platform']){
            $orders = Db::name('order')->where('platform',$data['platform'])->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['phone']){
            $map['phone'] = ['like',"%{$data['phone']}%"];
        }
        if ($data['name']){
            $map['name'] = ['like',"%{$data['name']}%"];
        }
        if ($data['booking_people_name']){
            $orders = Db::name('order')->where('booking_people_name','like',"%{$data['booking_people_name']}%")->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }
        if ($data['booking_people_phone']){
            $orders = Db::name('order')->where('booking_people_phone','like',"%{$data['booking_people_phone']}%")->select();
            $oid = '';
            if ($orders){
                foreach ($orders as $index08 => $order) {
                    $oid .= $order['id'].',';
                }
            }
            if ($map['oid'] && !empty($oid)){
                $oid = explode(',',$oid);
                $oids = '';
                foreach ($oid as $index33 => $item33) {
                    if (in_array($item33,explode(',',$map['oid'][1]))){
                        $oids .= $item33.',';
                    }
                }
                $map['oid'] = empty($oids)? '':rtrim($oids,',');
            }elseif(!empty($oid)){
                $map['oid'] = ['in',rtrim($oid,',')];
            }
        }

        //选择导出数据
        if ($data['id']){
            $id = implode($data['id'],',');
            $map['id'] = ['in',$id];
        }

        //查询要填充表格数据
        $map['isdelete'] = 0;
        $map['isaccommodation'] = '包含住宿';
        $list = Db::name('order_traveler')
            ->where($map)
            ->order('id','desc')
            ->select();
//        dump($list);die;
        //字段转换
        foreach ($list as $lk=>$lv) {
            unset($list[$lk]['isdelete']);
            unset($list[$lk]['status']);
            unset($list[$lk]['vehicle_adjustment']);
            unset($list[$lk]['room_adjustment']);
            unset($list[$lk]['remark']);
            unset($list[$lk]['start_time']);
            unset($list[$lk]['end_time']);
            unset($list[$lk]['order_processing_status']);
            $order = Db::name('order')->where('id',$lv['oid'])->find();
            $routeTitle = Db::name('route')->where('id',$order['route_id'])->value('title');
            $list[$lk]['group'] = empty($routeTitle) ? '': $routeTitle;
            $list[$lk]['booking_people_name'] = empty($order['booking_people_name']) ? '': $order['booking_people_name'];
            $list[$lk]['booking_people_phone'] = empty($order['booking_people_phone']) ? '': $order['booking_people_phone'];
            $list[$lk]['start_time'] = empty($order['start_time']) ? '': date('Y-m-d',$order['start_time']);
            $list[$lk]['end_time'] = empty($order['end_time']) ? '': date('Y-m-d',$order['end_time']);
            $platform = Db::name('platform')->where('platform_name',$order['platform'])->value('name');
            $list[$lk]['platform'] = empty($platform) ? '': $platform;
            $travellerInfo = Db::name('order_traveler')
                ->where('isaccommodation','包含住宿')
                ->where('oid',$lv['oid'])
                ->order('id','desc')
                ->select();
            $list[$lk]['oid'] = empty($order['order_id']) ? $lv['oid']: $order['order_id'];
            $list[$lk]['title'] = empty($order['title']) ? '': $order['title'];
            $list[$lk]['num'] = empty($travellerInfo) ? '': count($travellerInfo);
        }

        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店安排-控房统计数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }
}
